//
//  ZJToast.m
//  Pet
//
//  Created by babbage on 16/7/14.
//  Copyright © 2016年 babbage. All rights reserved.
//

#import "ZJToast.h"

#define kZJToastViewTag 875690

@implementation ZJToast

+ (UIView *)toastWithTitle:(NSString *)title
{
    UIView *toastView = [[UIView alloc]init];
    toastView.layer.cornerRadius = 3.f;
    toastView.layer.masksToBounds = YES;
    toastView.backgroundColor = [ZJToast colorFromHexString:@"222222"];
    toastView.layer.borderWidth = 0.5f;
    toastView.layer.borderColor = [ZJToast colorFromHexString:@"404040"].CGColor;
    toastView.tag = kZJToastViewTag;
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.text = title;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:14.f];
    titleLabel.textColor = [UIColor whiteColor];
    [titleLabel sizeToFit];
    
    toastView.size = CGSizeMake(titleLabel.width+ 2 * 10, titleLabel.height + 2*4);
    [toastView addSubview:titleLabel];
    titleLabel.centerX = toastView.width/2;
    titleLabel.centerY = toastView.height/2;
    
    return toastView;
}

+ (void)showToast:(NSString *)title
{
    if ([[[UIApplication sharedApplication] keyWindow] viewWithTag:kZJToastViewTag]) {
        [[[[UIApplication sharedApplication] keyWindow] viewWithTag:kZJToastViewTag] removeFromSuperview];
    }
    
    UIView *toastView = [ZJToast toastWithTitle:title];
    
    [[[UIApplication sharedApplication] keyWindow]addSubview:toastView];
    toastView.centerX = [[UIApplication sharedApplication] keyWindow].width/2;
    toastView.top = [UIScreen mainScreen].bounds.size.height - 120 - toastView.height;
    toastView.alpha = 0.f;
    
    [UIView animateWithDuration:0.26 animations:^{
        
        toastView.alpha = 1.f;
        
    } completion:^(BOOL finished) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [ZJToast makeToastHiddenAndRemove];
            
        });
        
    }];
}
+ (void)makeToastHiddenAndRemove
{
    UIView *toastView = [[[UIApplication sharedApplication] keyWindow] viewWithTag:kZJToastViewTag];
    
    [UIView animateWithDuration:0.26 animations:^{
        
        toastView.alpha = 0.f;
        
    } completion:^(BOOL finished) {
        
        [toastView removeFromSuperview];
        
    }];
}
+ (void)showToastError:(NSError *)error
{
    NSString *errMsg = [error.userInfo objectForKey:@"errMsg"];
    
    [ZJToast showToast:errMsg];
}





+ (UIColor *)colorFromHexString:(NSString *)hexString
{
    
    unsigned hexNum;
    if ( ![[NSScanner scannerWithString:hexString] scanHexInt:&hexNum] ) {
        return nil;
    }
    
    return [UIColor colorWithRed:((float)((hexNum & 0xFF0000) >> 16))/255.0 green:((float)((hexNum & 0xFF00) >> 8))/255.0 blue:((float)(hexNum & 0xFF))/255.0 alpha:1.0];
}

@end
